package net.ojbk.twobox;

import net.ojbk.twobox.pojo.TcpMessage;
import org.junit.Test;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;

/**
 * PACKAGE_NAME: net.ojbk.twobox
 * Description:
 */
public class TCPTest6 {
    @Test
    public void test1() throws InterruptedException {
        int localPort = -1; // 开始地址
        int timePeriod = 200; // 时间间隔
        int cycleTimes = 5; // 循环次数
        int[] outSidePorts = new int[cycleTimes];
        for (int i = 0; i < cycleTimes; i++) {
            Thread.sleep(timePeriod);
            Socket socket = new Socket();
            try {
                socket.setReuseAddress(true);
                if (localPort != -1)
                    socket.bind(new InetSocketAddress(localPort + i));
                localPort = socket.getLocalPort();
                socket.connect(new InetSocketAddress("ojbk.net", 9999));
                //System.out.println("建立链接,本地地址：" + socket.getLocalAddress().getHostAddress() + ":" + socket.getLocalPort());

                TcpMessage tcpMessage = new TcpMessage();
                tcpMessage.code = 5;
                ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
                ObjectInputStream objectInputStream = new ObjectInputStream(new BufferedInputStream(socket.getInputStream()));
                objectOutputStream.writeObject(tcpMessage);
                objectOutputStream.flush();
                // 接收
                TcpMessage responseMsg = (TcpMessage) objectInputStream.readObject();
                Object[] data = (Object[]) responseMsg.data;
                String ip = (String) data[0];
                int port = (int) data[1];
                outSidePorts[i] = port;
                System.out.println("外网地址：" + ip + ":" + port);
                // 断开
                objectInputStream.close();
                objectOutputStream.close();
                socket.close();
                //System.out.println("断开第一链接");
            } catch (IOException | ClassNotFoundException ignored) {
            }
        }
        for (int i : outSidePorts) {
            System.out.println(i);
        }
        System.out.println("循环次数：" + cycleTimes + "\n端口差值：" + (outSidePorts[cycleTimes - 1] - outSidePorts[0]));
    }
}
